
<template>
<!-- 供方预付款红单页面 -->
    <div class="e-form">
        <div class="tabs">
            <el-tabs tab-position="left" v-model="tabsName" @tab-click="onChangeTab">
                <el-tab-pane label="基本信息" name="baseInfo" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="附件信息" name="attach" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="审核历史" name="auditHistory" :disabled="clickTabFlag"></el-tab-pane>
                <div>
                    <div id="baseInfoCon" class="con">
                        <div class="tabs-title" id="baseInfo">基本信息</div>
                        <div style="width: 100%;" class="form">
                            <el-form :model="formData" ref="ruleForm" label-width="240px">
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="合同编号" prop="billNo">
                                            {{ formData.billNo }}
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="单据机构" prop="orgName">
                                            {{ formData.orgName }}
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="合同类型" prop="contractTypeValue">
                                            {{ formData.contractTypeName }}
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="合同名称" prop="contractBillId">
                                            {{ formData.contractName }}&nbsp;
                                            <span class="a" @click="onViewContract" v-if="formData.contractBillId">查看</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="结算单位" prop="settlementUnitId">
                                            {{ formData.settlementUnitName }}
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="结算日期" prop="settlementDate">
                                            {{ formData.settlementDate }}
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="预付款金额(元)" prop="amount">
                                            {{ formData.amount }}
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="币种" prop="currencyId">
                                            {{ formData.currency }}
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="累计预付款金额(元)" prop="cumulativeAmount">
                                            {{ formData.cumulativeAmount }}
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="冲预付款金额(元)" prop="writeOffAmount">
                                            {{ formData.writeOffAmount }}
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="本位币" prop="baseCurId">
                                            {{ formData.baseCurName }}
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="传输财务共享" prop="easId">
                                            {{ !formData.easId ? '未上传' : '已上传' }}
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="预付款金额(本位币)" prop="baseCurAmount">
                                            {{ formData.baseCurAmount }}&nbsp;
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="状态" prop="state">
                                            {{ formData.state ? getState(formData.state) : '' }}
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                    <el-form-item  label="红单状态" width="150">
                                        {{redTableState(formData)}}
                                    </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                    <el-form-item  label="红单标识" width="150">
                                           <span class="redView" :class="formData.state == 0 || formData.state==1?'redIdentifier':'identifier'">{{formData.state==0||formData.state==1?'红单':'已冲'}}</span>
                                    </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="24">
                                        <el-form-item label="备注" prop="remarks">
                                            <el-input
                                                type="textarea"
                                                :autosize="{ minRows: 2, maxRows: 4}"
                                                placeholder="请输入内容"
                                                v-model="formData.remarks"
                                                v-if="formData.state != 2"
                                            ></el-input>
                                            <span v-else>{{formData.remarks}}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                            </el-form>
                        </div>
                    </div>
                    <div id="attachCon" class="con">
                        <div class="tabs-title" id="attach">附件信息</div>
                         <attach-comp :relationId="billId" bucketName="supplierPayment" v-if="formData.state == 0"/>
                        <attach-comp v-else :relationId="billId" bucketName="supplierPayment" isView />
                    </div>
                    <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <ComExaHistory :billType="Number(billType)" @getAuditHistory="getAuditHistory" :tableData="auditHistoryData" ref="ComExaHistory" />
                    </div>
                </div>
            </el-tabs>
        </div>
        <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
        <div class="buttons">
            <ComExaButtons :auditState="auditState" @exas="exas" :founderId='formData.founderId' :state='formData.state'/>
            <el-button @click="onCancel" style="margin-left: 10px;">取消</el-button>
        </div>
    </div>
</template>

<script>
import { openAppClient, throttle } from '@/utils/common'
import AttachComp from '@/components/common/attachIndex'
// eslint-disable-next-line no-unused-vars
import request from '@/api/materialSettlement/supplierPayment'
//审核历史
import ComExaHistory from '@/components/common/exaHistory'
import ComExaButtons from '@/components/common/exaButtons'
import { mapState, mapMutations } from 'vuex'
import '@/utils/jquery.scrollTo.min'

let oldRouter = {} // 上一个页面来源
export default {
    components: {
        AttachComp,
        ComExaHistory,
        ComExaButtons,
    },
    data () {
        return {
            tabsName: 'baseInfo',
            billType: '1018',
            flowParams: {
                'billId': '',
                'billType': '',
                'freeNextUnitIndex': 0,
                'freeNextUser': '',
                'isPass': true,
                'isShareInAudit': true,
                'opinion': '',
                'orgId': '',
                'orgName': '',
                'userId': '',
                'workId': ''
            },
            //表单数据
            formData: {},
            orgId: '', //机构id
            orgName: '', //机构名称
            isSkip: false, //是否跳转
            val: '', //冲预付款金额（元）
            auditHistoryData: [],
            auditState: {},
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false,
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            winEvent: {}
        }
    },
    computed: {
        ...mapState('contract', ['ctClassify']),
        ...mapState('equip', ['equipData']),
        billId () {
            return this.$route.query.billid
        },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 120 - this.lastConHeight
        }
    },
    created () {
        this.flowParams.billId = this.$route.query.billid
        this.flowParams.billType = this.billType
    },
    mounted () {
        this.auditState = this.$route.params.auditState
        if (!this.auditState) {
            this.getCurrentUnitInfo()
        }
        this.getById()
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = ['baseInfo', 'attach', 'auditHistory']
        let $idsTop = []
        const onScroll = () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }
            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const $item = document.getElementById(item)
                    let itemTop = null
                    if ($item) {
                        itemTop = $item.offsetTop
                    }
                    return itemTop
                })
            }
            const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if (scrollTop + 1 >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        }
        this.winEvent.onScroll = onScroll
        window.addEventListener('scroll', this.winEvent.onScroll)
        this.screenWidth = document.documentElement.clientWidth
        this.screenHeight = document.documentElement.clientHeight
        const onResize = () => {
            this.screenWidth = document.documentElement.clientWidth
            this.screenHeight = document.documentElement.clientHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        }
        this.winEvent.onResize = throttle(onResize, 500)
        window.addEventListener('resize', this.winEvent.onResize)
    },
    beforeDestroy () {
        window.removeEventListener('scroll', this.winEvent.onScroll)
        window.removeEventListener('resize', this.winEvent.onResize)
    },
    beforeRouteEnter (to, from, next) {
        oldRouter = from
        next()
    },
    beforeRouteLeave (to, from, next) {
        oldRouter = null
        next()
    },
    methods: {
        ...mapMutations(['setSelectedInfo']),
        redTableState (row) {
            if(row.isRed == 1) {
                let str = ''
                if(row.state == 0 || row.state == 1) {
                    str = '冲销中'
                }else if(row.state == 2) {
                    str = '已冲'
                }
                return str
            }
        },
        async getById () {
            const res = await request.getPaymentById({
                id: this.billId
            })
            this.formData = res
        },
        async initRedData () {
            const res = await request.initRed({ billId: this.billId })
            this.formData = res
        },
        getCurrentUnitInfo () {
            request.getCurrentUnitInfo(this.flowParams).then(res => {
                this.auditState = res
            })
        },
        // 审核历史列表查询
        async getAuditHistory () {
            this.auditHistoryData = await request.getAuditHistory(this.flowParams)
        },
        //保存按钮
        onSave (str) {
            // 已有billId, 不必重复写
            return new Promise((resovle, reject) => {
                this.$refs['ruleForm'].validate(async valid => {
                    if (valid) {
                        try {
                            await request.paymentModify(this.formData)
                            if (str !== 'submit') {
                                this.clientPop('suc', '保存成功')
                            } else {
                                // 点击保存并提交
                                resovle()
                            }
                        } catch (error) {
                            reject(error)
                        }
                    }
                })
            })
        },
        //提交
        async onSubmit () {
            try {
                await this.onSave('submit')
                await request.flowCommit(this.flowParams)
                this.clientPop('suc', '提交成功', () => {
                    this.$router.replace('/supplierPayment')
                })
            } catch (error) {
                alert(error.message || '请求出错')
            }
        },
        async onDel () {
            try {
                await request.paymentDel({
                    id: this.billId
                })
                this.clientPop('suc', '删除成功', () => {
                    this.$router.replace('/supplierPayment')
                })
            } catch (error) {
                alert(error.message || '请求出错')
            }
        },
        async onAudit () {
            openAppClient('/exaDialog', '填写审核意见', () => {
                const auditParams = JSON.parse(localStorage.vuex).auditParams
                request.flowAudit({
                    'billId': this.billId,
                    'billType': this.billType,
                    'freeNextUnitIndex': 0,
                    'freeNextUser': '',
                    'isPass': auditParams.isPass,
                    'isShareInAudit': true,
                    'opinion': auditParams.opinion,
                    'orgId': '',
                    'orgName': '',
                    'userId': '',
                    'workId': ''
                }).then(() => {
                    this.clientPop('suc', '审核成功', () => {
                        this.$router.replace('/supplierPayment')
                    })
                })
            })
        },
        async onUndo () {
            try {
                await request.flowUndoAudit(this.flowParams)
                this.clientPop('suc', '撤回成功', () => {
                    this.$router.replace('/supplierPayment')
                })
            } catch (error) {
                alert(error.message || '请求出错')
            }
        },
        onNullify () {
            try {
                openAppClient('/nullifyDialog', '填写作废说明', async () => {
                    const auditParams = JSON.parse(localStorage.vuex).auditParams
                    await request.flowUndoAudit({
                        'billId': this.billId,
                        'billType': this.billType,
                        'nullifyCreated': '',
                        'nullifyCreator': '',
                        'nullifyCreatorId': '',
                        'nullifyDescription': auditParams.nullifyDescription,
                        'nullifyReason': auditParams.nullifyReason
                    })
                    this.clientPop('suc', '作废成功', () => {
                        this.$router.replace('/supplierPayment')
                    })
                })
            } catch (error) {
                alert(error.message || '请求出错')
            }
        },
        //取消按钮
        onCancel () {
            if (oldRouter.path === '/supplierPayment') {
                this.$router.back()
            } else {
                this.$router.replace('/supplierPayment')
            }
        },
        exas (str) {
            switch (str) {
            case 'submit':
                this.onSave()
                break
            case 'deleteData':
                this.onDel()
                break
            case 'submitCommit':
                this.onSubmit()
                break
            case 'audit':
                this.onAudit()
                break
            case 'undoAudit':
                this.onUndo()
                break
            case 'nullify':
                this.onNullify()
            }
        },
        onViewContract () {
            //1物资采购、2周材租赁、3加工、4设备采购、5设备租赁、6服务采购
            let url = ''
            let title = ''
            switch (this.formData.contractTypeValue) {
            case 1:
                url = 'ctMaterialApplyShow'
                title = '物资采购合同'
                break
            case 2:
                url = 'ctRevolvMaterialApplyShow'
                title = '周材租赁合同'
                break
            case 3:
                url = 'processingContractApplyShow'
                title = '加工合同'
                break
            case 4:
                url = 'ctEquipmentPurchaseApplyShow'
                title = '设备采购合同'
                break
            case 5:
                url = 'ctEquipmentLeaseApplyShow'
                title = '设备租赁合同'
                break
            case 6:
                url = 'serviceProcurementApplyShow'
                title = '服务采购合同'
                break
            }
            openAppClient(`/${url}?billid=${this.formData.contractBillId}&isview=true`, `查看${title}`)
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                const lastCon = document.getElementById('auditHistoryCon')
                if (lastCon) {
                    const lastConHeight = lastCon.offsetHeight
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        onChangeTab (e) {
            $.scrollTo(`#${e.name}`, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        getState (state) {
            const findObj = this.equipData.state.find(item => item.value === Number(state))
            return findObj ? findObj.label : ''
        },
    }
}
</script>

<style lang="scss" scoped>
.redView {
    width: 100%;
    height: 24px;
    color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
}
.redIdentifier {
    background-color: #FF2330;
}
.identifier {
     background-color: #999999;
}
.buttons {
    left: 0;
}
.e-form {
    margin-bottom: 80px;
    padding: 0 20px;
    .tabs-title::before {
        content: '';
        height: 22px;
        width: 8px;
        border-radius: 40px;
        background-color: #2e61d7;
        display: block;
        position: absolute;
        left: 20px;
        margin-right: 20px;
    }
}

.e-table {
    background: #fff;
}

.el-tab-pane {
    margin-left: -10px;
}
</style>
